import {
	getItem,
	setItem
} from "@/pages/im/util/storageHelper.js";
import store from "@/store";
import wfc from "@/wfc/client/wfc";
import Conversation from "@/wfc/model/conversation";
import ConversationType from "@/wfc/model/conversationType";
import {
	req
} from '@/common/vmeitime-http/'
import api from '@/common/api.js'
import {
	userStore
} from "@/pinia";

import {
	gendersignToIm
} from '@/utlis/common.js'

import Config from "@/config";


let jobId;
let hunterId;
let userFlag;
let currentUserId;
let toUserId;
let currentImFlag;

export let isJob;

const imUserFlag = [{
		name: '营销中心',
		flag: 'marketingCenter',
		value: 'a'
	},
	{
		name: '本地服务',
		flag: 'localService',
		value: 'b'
	},
	{
		name: '招商中心',
		flag: 'investmentCenter',
		value: 'c'
	},
	{
		name: '客服',
		flag: 'customerService',
		value: 'd'
	},
	{
		name: '招聘',
		flag: 'recruitment',
		value: 'e'
	},
	{
		name: '短时工',
		flag: 'shotwork',
		value: 'f'
	}
]

const handleImFlag = (userId) => {
	const imUser = imUserFlag.find(im => im.flag === currentImFlag);
	const id = `${userId}-${imUser.value}`;
	return id;
}

let currentCallback;
let pushcallback
/**
 * @description im初始化
 * @param imFlag 模块标志 marketingCenter localService investmentCenter customerService recruitment
 * @param toUserId 对方用户id
 * @param jobId 岗位id
 * @param callback 回调函数
 */
export const init = (options, callback = null) => {
	console.log('call router2.push({',callback);
	const userStoreInfo = userStore();
	const userId = userStoreInfo.userInfo.id;
	pushcallback = callback;
	const {imFlag, toUserId, jobId } = options;
	currentCallback = () => {
		setConversation(toUserId, jobId);
	}
	imLogin(userId, imFlag);
}

const imCofig = {
	baseUrl: `http://${Config.IM_SERVER_HOST}:18080`,
	header: gendersignToIm()
}
// 获取token
const imLogin = (id, imFlag) => {
	currentImFlag = imFlag;
	currentUserId = handleImFlag(id);
	const genderSign = gendersignToIm();
	imGetInfo();
}
const imGetInfo = (id) => {
	console.log('imGetInfo 开始',currentUserId);

	req('POST', '/admin/user/get_info', {
			userId: currentUserId,
		},
		imCofig
	).then((r) => {
		console.log('查询用户是否存在：', r);
		if (r.code == 0) {
			getImToken()
		} else {
			imRegist()
		}
	})
}

const imRegist = () => {
	const userStoreInfo = userStore();
	req('POST', '/admin/user/create', {
			userId: currentUserId,
			name: currentUserId,
			displayName: userStoreInfo.userInfo.nickname
			// clientId: wfc.getClientId(),
			// platform: Config.getWFCPlatform(),

		},
		imCofig
	).then(res => {
		console.log('im注册：', res);
		if (res.code == 0) {
			getImToken()
		}
	})
}

const getImToken = () => {
	console.log('开始获取token: >>');
	const userStoreInfo = userStore();
	req('POST', '/admin/user/get_token', {
			userId: currentUserId,
			clientId: wfc.getClientId(),
			platform: Config.getWFCPlatform(),
		},
		imCofig
	).then((r) => {
		console.log('获取token: >>', r);
		const {
			code,
			msg,
			result
		} = r;
		if (code === 0) {
			userStoreInfo.doImLogin(r);
			let {
				userId,
				token
			} = result;
			console.log('登录获取userId', {
				userId,
				token
			});

			console.log('开始连接im服务器');
			wfc.registerMessageContent('phoneMessage', false, ConversationType.Single);
			wfc.connect(userId, token);

			setItem('userId', userId);
			setItem('token', token);
			
			// 间隔，确保wfc服务器连接成功
			setTimeout(() => {
				currentCallback();
			}, 500);
		} else {
			uni.showToast({
				title: msg,
				icon: 'none'
			})
		}
	})
}


// 设置会话
export const setConversation = (toUserId = 'ib6qmws2k', jobid) => {
	// 判断聊天是基于岗位聊天还是正常聊天
	if (!jobid) {
		isJob = false;
	} else {
		jobId = jobid;
		isJob = true;
	}

	// 获取存储信息
	const userStoreInfo = userStore();
	userFlag = userStoreInfo.userFlag;


	// if (process.env.NODE_ENV === 'development') { // 开发时测试使用
	// 	const userId = getItem('userId') || wfc.getUserId();
	// 	if (userId == "1678241097429176322-e") {
	// 		toUserId = "1684802836232736770-e"			
	// 	} else {
	// 		toUserId = "1678241097429176322-e"
	// 	}
	// }

	hunterId = toUserId;

console.log('创建的参数',toUserId,jobid);
toUserId = handleImFlag(toUserId)
	store._loadDefaultData();
	const conversationList = store.state.conversation.conversationInfoList;
	// const currentConversation = conversationList.find(item => item.conversation.target == toUserId);
	const filteredConversations = conversationList.filter(item => item.conversation.target == toUserId);
	const sortedConversations = filteredConversations.sort((a, b) => b.timestamp - a.timestamp);
	const currentConversation = sortedConversations[0];
	console.log('查询本地的当前用户信息',currentConversation);
	//如果是招聘页面  记录jobid
	if(isJob){
		userFlag = userStoreInfo.userFlag;
		let par = {
			paramCode:jobId,
			paramType:10,
			paramValue:'',
			remark:''
		}
		if (userFlag == 0) { // 应聘者
			par.paramValue=userStoreInfo.userInfo.id
			par.remark=toUserId.split('-')[0]
		} else {
			par.paramValue=toUserId.split('-')[0]
			par.remark=userStoreInfo.userInfo.id
		}
		req('POST',api.putJobId,par).then(()=>{
			// 获取会话列表
			if (currentConversation) {
				store.setCurrentConversationInfo(currentConversation);
				pushcallback&&pushcallback()
				return;
			}
			
			// 不存在会话的话就新建
			let conversation = new Conversation(ConversationType.Single, toUserId, 0);
			console.log('我长这个样子带jobid',conversation);
			store.setCurrentConversation(conversation);
			pushcallback&&pushcallback()
		})
	}else{
		// 获取会话列表
		if (currentConversation) {
			store.setCurrentConversationInfo(currentConversation);
			pushcallback&&pushcallback()
			return;
		}
		
		// 不存在会话的话就新建
		let conversation = new Conversation(ConversationType.Single, toUserId, 0);
		console.log('我长这个样子',conversation);
		store.setCurrentConversation(conversation);
		pushcallback&&pushcallback()
	}

	
}

/** 
 * @description: 查看沟通记录
 * @return {Promise} Promise
 */
export const getJobContact = () => {
	// if (process.env.NODE_ENV === 'development') {
	// 	jobId = '1679001602632998913';
	// }

	// 获取存储信息
	const userStoreInfo = userStore();
	userFlag = userStoreInfo.userFlag;

	if (userFlag == 0) { // 应聘者
		return req('POST', api.jobContact, {
			jobId,
		});
	} else if (userFlag == 2) {
		return req('POST', api.jobContact2, {
			jobId,
			hunterId,
		});
	}
}

// 是否沟通过
export const isContact = async () => {
	let bol = false;

	const job = await getJobContact();
	const {
		success,
		result
	} = job;

	if (!success) return bol;

	const keys = ['isPhone1', 'isWx1', 'isResume1', 'isWx2', 'isPhone2', 'isResume2', 'notice'];
	keys.forEach((key) => {
		if (result[key] != 0) bol = true;
	})

	return bol;
}

// 职位-应聘者向HR互动通用接口字段对照表，用不到了
const interactionDic = {
	user2HrPhone: 'isPhone1',
	user2HrWx: 'isWx1',
	user2HrResume: 'isResume1',
	hr2UserPhone: 'isPhone2',
	hr2UserWx: 'isWx2',
	hr2UserResume: 'isResume2',
	notice: 'notice'
}

export const getInteractionDic = (key, isReversed = false) => {
	console.log('getInteractionDic', key, isReversed, userFlag);
	// userFlag 0/2 对应字段规律处理
	let obj;
	if (userFlag == 0) {
		obj = !isReversed ? {
			phone: `isPhone1`,
			wx: `isWx1`,
			resume: `isResume1`,
			notice: 'notice'
		} : {
			phone: `isPhone2`,
			wx: `isWx2`,
			resume: `isResume2`,
			notice: 'notice'
		};
	} else  {
		obj = !isReversed ? {
			phone: `isPhone2`,
			wx: `isWx2`,
			resume: `isResume2`,
			notice: 'notice'
		} : {
			phone: `isPhone1`,
			wx: `isWx1`,
			resume: `isResume1`,
			notice: 'notice'
		};
	}

	return obj[key];
}

/** 
 * @description: 职位-应聘者与HR互动通用接口
 * @param {type} jobId
 * @return {type}
 */
export const setImInteraction = (key, value,jobid,hunterid) => {
	let url;
	let obj;
	if (userFlag == 0) { // 应聘者
		url = api.imInteraction;
		obj = {
			jobId:jobid,
			[key]: value,
		}
	} else { // 供应商
		url = api.imInteraction2;
		obj = {
			jobId:jobid,
			hunterId:hunterid,
			[key]: value,
		}
	}
	return req('POST', url, obj);
}

/** 
 * @description: 获取在线简历
 * @param {type} jobId
 * @return {type}
 */
export const getResume = () => {
	return req('GET', api.meiyeRecruitHunterInfo2Details);
}

class ImEvent {
	map = {};

	constructor() {}

	$emit(name, params) {
		if (this.map[name] != null) {
			for (let work of this.map[name]) {
				if (work != null) {
					work(params);
				}
			}
		} else {
			console.warn("正在触发无效的监听事件，事件名称为：" + name);
		}
	}

	$on(name, work) {
		if (this.map[name] == null) this.map[name] = [];
		this.map[name].push(work);
	}

	$off(name) {
		delete this.map[name];
	}
}

export const imEvent = new ImEvent();